<template>
  <breadcrumb></breadcrumb>
  <!-- 用户列表 -->
  <div class="id">
    <!-- 头部搜索 和添加用户 -->
    <div class="search">
      <el-row>
        <el-input placeholder="请输入搜索名字" class="input" v-model="queryInfo.query" clearable @clear="getUesrList">
          <template #append>
            <el-button :icon="Search" @click="getUesrList" />
          </template>
        </el-input>
        <el-button class="btn" type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </el-row>
    </div>
    <!-- 用户表内容 -->
    <div class="contaion">
      <el-table :data="state" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="姓名" width="180" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row.id, scope.row.mg_state)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" #default="scope">
          <el-button type="primary" :icon="EditPen" size="small" @click="showEditDialog(scope.row.id)"></el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="delUsers(scope.row.id)"></el-button>
          <el-button type="warning" :icon="Setting" size="small" @click="showRoleDialog(scope.row)"></el-button>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加用户的对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加用户" width="50%" align-center>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddUsers(addFormRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改用户" width="50%" align-center>
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditUsers(editFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" v-model="roleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :current-change="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div> 
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import {
  getUser,
  addUsers,
  getUsers,
  editUsers,
  editState,
  deltUsers,
  setUserRole
} from "@/apis/user";
import { getRolesList } from '@/apis/power'
import { Search, EditPen, Delete, Setting } from "@element-plus/icons-vue";
const addFormRef = ref(null);
const editFormRef = ref(null);
//用户列表信息
const state = ref([]);
//添加弹出框是否显示
const addDialogVisible = ref(false);
//编辑弹出框是否显示
const editDialogVisible = ref(false);
//当前页数
const currentPage = ref(1);
//当前总条数
const total = ref(0);
//当前一页显示多少条
const pageSize = ref(5);
// 查询用户列表的参数对象
const queryInfo = reactive(
  {
    query: "",
    pagenum: 1, // 页码
    pagesize: 5, // 页大小
  }
)

const editForm = reactive({});

//获取用户列表
const getUesrList = () => {
  getUser(queryInfo).then(({ data: res }) => {
    state.value = res.users;
    total.value = res.total;
  });
};
//改变页码大小
const handleSizeChange = (pagesize) => {
  queryInfo.pagesize = pagesize;
  getUesrList();
};
//改变页数
const handleCurrentChange = (pagechange) => {
  queryInfo.pagenum = pagechange;
  getUesrList();
};
//定义规则
const addFormRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 10,
      message: "长度在 3 到 10 个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 15,
      message: "长度在 6 到 15 个字符",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
      message: "邮箱格式不正确",
      trigger: "blur",
    },
  ],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
});
const editFormRules = reactive({
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
      message: "邮箱格式不正确",
      trigger: "blur",
    },
  ],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
});
//添加用户
const addForm = reactive({
  username: "",
  password: "",
  email: "",
  mobile: "",
});
//添加用户
const handleAddUsers = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addUsers(addForm).then((res) => {
        console.log(res);
        if (res.meta.status !== 201) {
          ElMessage.error('添加用户失败')
        } else {
          console.log(res);
          getUesrList();
          addDialogVisible.value = false;
          ElMessage.success('添加用户成功')
        }

      });
    } else {
      console.log('error submit!', fields)
    }
  })
}
//显示编辑用户对话框
const showEditDialog = (id) => {
  // console.log(id);
  editDialogVisible.value = true;
  getUsers(id).then(({ data: res }) => {
    editForm.id = res.id;
    editForm.username = res.username;
    editForm.mobile = res.mobile;
    editForm.email = res.email;
  });
};

//编辑用户
const handleEditUsers = async (editFormRef) => {
  //   //修改用户信息
  const editInfo = reactive({
    email: editForm.email,
    mobile: editForm.mobile,
  });
  if (!editFormRef) return
  await editFormRef.validate((valid, fields) => {
    if (valid) {
      editUsers(editForm.id, editInfo).then(() => {
        getUesrList();
        editDialogVisible.value = false
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//修改用户状态
const userStateChange = (id, mg_state) => {
  editState(id, mg_state).then(({ meta }) => {
    if (meta.status == 200) {
      getUesrList();
      ElMessage({
        type: "success",
        message: "更新用户状态成功",
      });
    } else {
      ElMessage({
        type: "info",
        message: "更新用户状态失败",
      });
    }
  });
};


//删除用户信息
const delUsers = (id) => {
  // deltUsers(id).then(({data,meta})=>{
  //   // confirm(meta.msg)
  //   getUesrList()
  // })
  ElMessageBox.confirm("确认要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deltUsers(id).then(({ mets }) => {
        getUesrList();
      });
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败",
      });
    });
};

//分配角色
const roleDialogVisible = ref(false)
const setRoleDialogClosed = () => {
  roleDialogVisible.value = false
  selectedRoleId.value = null
  userInfo = {}
}
const rolesList = ref([])
let userInfo = reactive({
  username: '',
  role_name: '',
  id: ''
})
const selectedRoleId = ref(null)
const showRoleDialog = async (rowInfo) => {
  console.log(rowInfo);
  userInfo.username = rowInfo.username
  userInfo.role_name = rowInfo.role_name
  userInfo.id = rowInfo.id
  //获取角色列表
  const res = await getRolesList()
  if (res.meta.status !== 200) {
    return ElMessage.error('你没有权限设置')
  }
  rolesList.value = res.data
  roleDialogVisible.value = true
}
const allotRole = async () => {
  //判断是否选择角色
  if (!selectedRoleId) {
    return ElMessage.error('请选择角色')
  }
  const res = await setUserRole(userInfo.id, selectedRoleId.value)
  console.log(res);
  if (res.meta.status !== 200) {
    return ElMessage.error('更新角色失败')
  }
  ElMessage.success('更新角色成功!')
  getUesrList()
  roleDialogVisible.value = false
}
onMounted(() => {
  getUesrList();
});
</script>

<style lang="scss">
.search {
  height: 40px;

  .input {
    width: 280px;
    height: 40px;
    margin-right: 20px;
  }

  .btn {
    height: 40px;
  }
}
</style>
